<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\Position as Pos;
use app\common\model\Friendship;
use app\common\model\Prize;
use think\Log;
/**
 * 会员接口
 */
class Position extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();


    }
    
    public function save(){
        $latitude = $this->request->post('latitude');
        $longitude = $this->request->post('longitude');
        $altitude = $this->request->post('altitude');
        $user = $this->auth->getUser();
        Log::record(43434343);
        Log::record($latitude);
        Log::record($longitude);
        Log::record($altitude);
        Log::record($user->id);
        Pos::create(['latitude' => $latitude, 'longitude' => $longitude, 'altitude' => $altitude, 'user_id' => $user->id]);
        $this->success('保存位置成功');
    }
    
    // 查询朋友最新位置
    public function getFriendPos(){
        $id = $this->request->post('id');
        Log::record(5454545);
        Log::record($id);
        $friend = Pos::where('user_id', $id)->order('create_time', 'desc') // 按创建时间降序
            ->limit(1) // 限制结果集为1条记录
            ->find(); // 查找单条记录;
        Log::record($friend);
        // 获取当前时间戳
        $timestamp = time();
        
        // 格式化当前时间
        $formattedTime = date('Y-m-d H:i:s', $timestamp);
        
        $this->success('查询成功', ['newPos' => $friend, 'time' => $formattedTime]);
    }

    // 查询朋友基本信息
    public function getBase(){
        $id = $this->request->post('id');
        $count_p = Pos::where('user_id', $id)->count();
        // 查询好友数量
        $count_f = Friendship::where('user_id1', $id)->whereOr('user_id2', $id)->count();
        // 查询赞助得分
        $totalPrize = Prize::where('userid', $id)->where('paid', 1)->sum('money');
        
        // 计算排名
        $list = Prize::where('paid', 1)->field("userid,sum(money) as totalMoney")->group('userid')->order('totalMoney', 'desc')->select();
       
        $index = 0;
        foreach ($list as $key => $value) {
            if ($value->userid == $id) {
                    $index = $key + 1;
                }
        };
        $index === 0 && $index = '--';
        
        $this->success('查询朋友基本信息成功', ['count_p' => $count_p, 'count_f' => $count_f, 'totalPrize' => $totalPrize, 'index' => $index]);
    }

}










